import java.util.Random;

public class MyBlockedQueue_自定义阻塞队列 {
    static class MyBlcokQueue {
        private int frist; //队首
        private int last; //队尾
        private int size; //队列实际的存储长度
        private int[] items; // 存储内容的容器

        //构造方法
        public MyBlcokQueue(int capaCity) {
            this.size = 0;
            this.frist = 0;
            this.last = 0;
            this.items = new int[capaCity];
        }

        /**
         * 入队
         */
        public void offer(int val) throws InterruptedException {
            synchronized (this) {
                if(size == items.length) {
                    // 队列已满，阻塞等待
                    this.wait();
                }
                items[last++] = val;
                size++;
                // 判断是否是最后一个元素
                if(last == items.length) {
                    last = 0;
                }
                // 唤醒任务
                this.notify();
            }
        }
        /**
         * 出队
         */
        public int poll() throws InterruptedException {
            int result = 0;
            synchronized (this) {
                if(size == 0) {
                    // 队列中没有任务了，不需要出队
                    this.wait();
                }
                result = items[frist++];
                size--;
                if(frist == items.length) {
                    // 队列又满了
                    frist = 0;
                }
                this.notify();
            }
            return result;
        }
    }

    public static void main(String[] args) {
        MyBlcokQueue myBlcokQueue = new MyBlcokQueue(10);
        // 1.生产数据
        Thread thread1 = new Thread(() -> {
            while (true) {
                // 生成随机数据
                int num = new Random().nextInt(10);
                try {
                    System.out.println("添加数据：" + num);
                    // 添加数据
                    myBlcokQueue.offer(num);
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();

        // 2.消费数据
        Thread thread2 = new Thread(() -> {
            while (true) {
                try {
                    int resdult = myBlcokQueue.poll();
                    System.out.println("消费数据：" + resdult);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
    }
}












